package com.deuwise.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.deuwise.system.entity.*;
import com.deuwise.system.entity.vo.LayerVo;
import com.deuwise.system.entity.vo.MapViewVo;
import com.deuwise.system.service.*;
import io.swagger.annotations.*;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import com.deuwise.common.utils.R;
import com.deuwise.common.utils.Result;
import com.baomidou.mybatisplus.plugins.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;

/**
 *@author deuwise
 *@date 2020-06-08 17:22:30
 */
@Api(tags = "地图视图配置模块", description = "地图视图配置")
@RequestMapping("system/sysMapViews")
@RestController()
public class SysMapViewsController extends AbstractController{
    @Autowired
    private SysMapViewsService sysMapViewsService;
    @Autowired
    private SysMapViewsDictService sysMapViewsDictService;
    /*视图配置图层集合*/
    @Autowired
    private SysMapLayersService sysmaplayersService;
    @Autowired
    private SysLayerService sysLayerService;
    /**应用-图层关联关系*/
    @Autowired
    private SysSiteLayerService layerService;
    @Autowired
    private AppDoService appDoService;

    @ApiOperation(value = "获取list", notes = "")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键标识", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "视图名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "typeName", value = "地图类型名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "version", value = "版本号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "currentPage", value = "开始页数", defaultValue = "1", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页多少条", defaultValue = "15", dataType = "int", paramType = "query")})
    public Result<Page<SysMapViews>> list(String id, String name, String typeName, String version){
        Wrapper<SysMapViews> wrapper = new EntityWrapper<SysMapViews>();
        if(StringUtils.isNotBlank(id)){
            wrapper.eq("id", id);
        }
        if(StringUtils.isNotBlank(name)){
            wrapper.like("name", name);
        }
        if(StringUtils.isNotBlank(typeName)){
            wrapper.like("type_name", typeName);
        }
        if(StringUtils.isNotBlank(version)){
            wrapper.eq("version", version);
        }
        Page<SysMapViews> listPage = sysMapViewsService.selectPage(getPage(SysMapViews.class),wrapper);
        for(SysMapViews sysMapViews : listPage.getRecords()){
            Wrapper<SysMapLayers> wrapperLayers = new EntityWrapper<SysMapLayers>();
            wrapperLayers.eq("map_views_id", sysMapViews.getId());
            List<SysMapLayers> layers = sysmaplayersService.selectList(wrapperLayers);
            sysMapViews.setLayers(layers);
        }
        return Result.ok(listPage);
    }

    @ApiOperation("删除字典")
    @DeleteMapping("/{id}")
    public R delete(@PathVariable("id") String id){

        sysMapViewsService.deleteById(id);
        // 删除图层集合
        Wrapper<SysMapLayers> wrapper = new EntityWrapper<SysMapLayers>();
        wrapper.eq("map_views_id", id);
        sysmaplayersService.delete(wrapper);
        return R.ok();
    }

    @GetMapping("/addViewJsonModel")
    @ApiOperation(value = "获取新增地图视图模板(JSON)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "typeName", value = "地图类型名称", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "version", value = "版本号", dataType = "String", paramType = "query", required = true)})
    public Result<JSONObject> addViewJsonModel(String typeName, String version){
        Wrapper<SysMapViewsDict> wrapper = new EntityWrapper<SysMapViewsDict>();
        wrapper.eq("type_name", typeName);
        wrapper.eq("version", version);
        List<SysMapViewsDict> doList=  sysMapViewsDictService.selectList(wrapper);

        if(null == doList || 0 == doList.size()){
            return Result.build(500, "该地图类型在视图字典中不存在!");
        }
        Class cls = SysLayerDict.class;
        //获取父节点属性是public的
        Field[] fields = cls.getFields();
        JSONObject jsonObject=new JSONObject(new LinkedHashMap());
        for (SysMapViewsDict sysMapViewsDict : doList){
            jsonObject.put(sysMapViewsDict.getField(),"");
        }
        return Result.ok(jsonObject);
    }

    @ApiOperation(value = "视图配置json类型新增")
    @RequestMapping(value = "/insertLayerJson", method = RequestMethod.POST)
    public R insertLayerJson(@RequestBody MapViewVo mapViewVo){
        try {
            if (null == mapViewVo || null == mapViewVo.getViewCenterJson()
                    || 0 == mapViewVo.getViewCenterJson().size()) {
                return R.error(500, "视图内容不能为空！");
            }
            SysMapViews sysMapViews = new SysMapViews();
            sysMapViews.setName(mapViewVo.getName());
            sysMapViews.setTypeName(mapViewVo.getTypeName());
            sysMapViews.setVersion(mapViewVo.getVersion());
            sysMapViews.setViewCenter(mapViewVo.getViewCenterJson().toJSONString());
            sysMapViews.setBaseMap(mapViewVo.getBaseMap());
            sysMapViews.setGround(mapViewVo.getGround());
            if(StringUtils.isNotBlank(mapViewVo.getId())){
                sysMapViews.setId(mapViewVo.getId());
            }
            sysMapViewsService.insertOrUpdate(sysMapViews);
            // 删除图层集合
            Wrapper<SysMapLayers> wrapper = new EntityWrapper<SysMapLayers>();
            wrapper.eq("map_views_id", sysMapViews.getId());
            sysmaplayersService.delete(wrapper);
            // 添加图层集合
            List<String> idList = mapViewVo.getLayerIds();
            if(null != idList && 0 < idList.size()){
                List<SysMapLayers> insertMapLayers = new ArrayList<>();
                for(String layerId : idList){
                    SysMapLayers sysMapLayers = new SysMapLayers();
                    sysMapLayers.setLayerId(layerId);
                    sysMapLayers.setMapViewsId(sysMapViews.getId());
                    insertMapLayers.add(sysMapLayers);
                }
                sysmaplayersService.insertBatch(insertMapLayers);
            }
            return  R.ok(sysMapViews.getId());
        }catch (Exception ex){
            return  R.error(ex.toString());
        }
    }

    /**
     * 获取编辑的图层信息
     */
    @ApiOperation(value = "根据ID获取编辑的视图信息", notes = "")
    @RequestMapping(value = "/getViewInfoById", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键标识", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "showAll", value = "是否显示所有(包含空值),0:否,1:是", defaultValue = "0", dataType = "int", paramType = "query")})
    public Result<MapViewVo> getViewInfoById(String id, int showAll) {
        MapViewVo mapViewVo = new MapViewVo();
        SysMapViews sysMapViews = sysMapViewsService.selectById(id);
        if(null != sysMapViews){
            JSONObject jsonObjectData = JSONObject.parseObject(sysMapViews.getViewCenter());
            if(1 == showAll){
                // 根据layerName 获取对应图层字典
                Result<JSONObject> result = addViewJsonModel(sysMapViews.getTypeName(), sysMapViews.getVersion());
                JSONObject jsonObject =result.getData();
                // 附加空值的属性
                for(String k : jsonObjectData.keySet()){
                    Object value = jsonObjectData.get(k);
                    if(jsonObject.containsKey(k)){
                        // 存在，赋值
                        jsonObject.put(k, value);
                    }
                }
                sysMapViews.setViewCenter(jsonObject.toJSONString());
            }
            Wrapper<SysMapLayers> wrapperLayers = new EntityWrapper<SysMapLayers>();
            wrapperLayers.eq("map_views_id", sysMapViews.getId());
            List<SysMapLayers> layers = sysmaplayersService.selectList(wrapperLayers);
            sysMapViews.setLayers(layers);

            List<String> layerIds = new ArrayList<>();
            for(SysMapLayers mapLayers : layers){
                layerIds.add(mapLayers.getLayerId());
            }

            // 转换格式返回
            mapViewVo.setBaseMap(sysMapViews.getBaseMap());
            mapViewVo.setGround(sysMapViews.getGround());
            mapViewVo.setId(sysMapViews.getId());
            mapViewVo.setName(sysMapViews.getName());
            mapViewVo.setLayerIds(layerIds);
            mapViewVo.setTypeName(sysMapViews.getTypeName());
            mapViewVo.setVersion(sysMapViews.getVersion());
            mapViewVo.setViewCenterJson(JSONObject.parseObject(sysMapViews.getViewCenter()));
        }
        return Result.ok(mapViewVo);
    }

    @ApiOperation(value = "获取视图列表", notes = "")
    @RequestMapping(value = "/viewList", method = RequestMethod.GET)
    public R viewList(){
        Wrapper<SysMapViews> wrapper = new EntityWrapper<SysMapViews>();
        List<SysMapViews> list = sysMapViewsService.selectList(wrapper);
        for(SysMapViews sysMapViews : list){
            sysMapViews.setViewCenter("");
        }
        return R.ok(list);
    }

    @ApiOperation(value = "获取视图json(gis使用)")
    @GetMapping("/useView")
    public Result<JSONObject> useView(@RequestParam(value = "version",required = false)String version,@RequestParam(value = "dimension",required = false)String dimension,@RequestParam(value = "code",required = false)String code) {
        JSONObject jsonObjects = new JSONObject();
        try{
            if(StringUtils.isNotBlank(code)) {
                Wrapper<AppDo> appDoWrapper = new EntityWrapper<>();
                appDoWrapper.eq("code", code);
                AppDo appDo = appDoService.selectOne(appDoWrapper);

                if (appDo == null) {
                    return Result.ok(jsonObjects);
                }
                String mapViewId = layerService.queryMapViewBySiteId(appDo.getId(), dimension);
                if (StringUtils.isBlank(mapViewId)) {
                    return Result.ok(jsonObjects);
                }
                // 查询视图
                Wrapper<SysMapViews> wrapper = new EntityWrapper<SysMapViews>();
                wrapper.eq("id", mapViewId);
                SysMapViews sysMapViews = sysMapViewsService.selectOne(wrapper);
                if(null != sysMapViews){
                    if(StringUtils.isNotBlank(sysMapViews.getViewCenter())){
                        jsonObjects.put("view", JSONObject.parseObject(sysMapViews.getViewCenter()));
                    }else{
                        jsonObjects.put("view", new JSONObject());
                    }
                    jsonObjects.put("basemap", sysMapViews.getBaseMap());
                    jsonObjects.put("ground", sysMapViews.getGround());

                    List<JSONObject> layerObj = new ArrayList<>();
                    // 配置图层列表
                    Wrapper<SysMapLayers> wrapperLayers = new EntityWrapper<SysMapLayers>();
                    wrapperLayers.eq("map_views_id", sysMapViews.getId());
                    List<SysMapLayers> layers = sysmaplayersService.selectList(wrapperLayers);
                    for(SysMapLayers sysMapLayers : layers){
                        // 获取图层信息
                        Wrapper<SysLayer> wrapper1 = new EntityWrapper<>();
                        wrapper1.eq("id", sysMapLayers.getLayerId());
                        SysLayer sysLayer = sysLayerService.selectOne(wrapper1);
                        if(null != sysLayer && StringUtils.isNotBlank(sysLayer.getLayerDataStr())){
                            layerObj.add(JSON.parseObject(sysLayer.getLayerDataStr()));
                        }
                    }
                    jsonObjects.put("layers", layerObj);
                }
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }

        return Result.ok(jsonObjects);
    }

    /**
     * 按条件查询视图
     * @param typeName
     * @param name
     * @param version
     * @return
     */
    public SysMapViews selectParam(String typeName, String name, String version){
        Wrapper<SysMapViews> wrapper = new EntityWrapper<>();
        if(StringUtils.isNotBlank(typeName)){
            wrapper.eq("type_name", typeName);
        }
        if(StringUtils.isNotBlank(name)){
            wrapper.eq("name", name);
        }
        if(StringUtils.isNotBlank(version)){
            wrapper.eq("version", version);
        }
        List<SysMapViews> list = sysMapViewsService.selectList(wrapper);
        if(0 < list.size()){
            return list.get(0);
        }
        return null;
    }
}